package com.openvid.webrtc.openvid.decoder;


import java.io.File;
import java.nio.ByteBuffer;
import java.util.LinkedList;
import java.util.Queue;

public class FilesDecoder {

    private VideoDecoderThread mVideoDecoder;
    private AudioDecoderThread mAudioDecoder;

    private boolean isRunning=false;

    private Queue<File> mFiles= new LinkedList<File>();
    private IDecoderData mCallback;

    public void addFile(File file){
        mFiles.add(file);
    }

    public void addDirectory(File directory,String suffix){
        if (directory.isDirectory()){
            for (File f:directory.listFiles()) {
                if (f.getName().endsWith(suffix)){
                    mFiles.add(f);
                }
            }
        }
    }

    public void start(IDecoderData callback){
        if (isRunning){
            return;
        }
        isRunning=true;

        File file=mFiles.poll();
        if (file==null){
            isRunning=false;
            return;
        }

        mCallback=callback;

        if (mVideoDecoder!=null){
            mVideoDecoder.interrupt();
            mVideoDecoder=null;
        }
        mVideoDecoder=new VideoDecoderThread(file, new VideoDecoderThread.IVideoData() {
            @Override
            public void onVideoFrame(ByteBuffer buffer, int width, int height, long ts) {
                if (mCallback!=null){
                    mCallback.onVideoFrame(buffer,width,height,ts);
                }
            }

            @Override
            public void onVideoEnd(File f) {

            }
        });

        mVideoDecoder.start();


        if (mAudioDecoder!=null){
            mAudioDecoder.interrupt();
            mAudioDecoder=null;
        }
        mAudioDecoder=new AudioDecoderThread(file, new AudioDecoderThread.IAudioData() {
            @Override
            public void onAudioFrame(byte[] data, long ts) {
                if (mCallback!=null){
                    mCallback.onAudioFrame(data,ts);
                }
            }

            @Override
            public void onAudioEnd(File f) {

            }
        });

        mAudioDecoder.start();

    }


    public void stop(){
        if (mVideoDecoder!=null){
            mVideoDecoder.interrupt();
            mVideoDecoder=null;
        }
        if (mAudioDecoder!=null){
            mAudioDecoder.interrupt();
            mAudioDecoder=null;
        }
    }

    public interface IDecoderData{
        void onVideoFrame(ByteBuffer buffer,int width,int height,long ts);
        void onAudioFrame(byte[] f,long ts);
    }
}
